package com.qf.service.impl;

import com.qf.dao.repository.RotationRepository;
import com.qf.pojo.po.RotationImage;
import com.qf.pojo.resp.BaseResp;
import com.qf.service.RotationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * @author lipengg
 * @date 2021/10/20
 */
@Service
public class RotationServiceImpl implements RotationService {

    @Autowired
    private RotationRepository rotationRepository;

    @Autowired
    private RedisTemplate redisTemplate;

    protected Logger logger = LoggerFactory.getLogger(RotationServiceImpl.class);

    @Override
    public BaseResp isFindRotation() {
        //首先在redis当中获取看是否存在
        Boolean rotation_list = redisTemplate.hasKey("rotation_list");
        Set rotation_list1 = null;
        if (!rotation_list){
            //redis中没有的时候走数据库查
            List<RotationImage> start = rotationRepository.findByStatus("start");
            logger.info("从数据库获取轮播图:"+start);
            for (RotationImage rotationImage : start) {
                redisTemplate.opsForZSet().add("rotation_list", rotationImage, rotationImage.getImageIndex());
            }
            //从redis中获取
            rotation_list1 = redisTemplate.opsForZSet().reverseRange("rotation_list", 0, -1);
        } else {
            rotation_list1 = redisTemplate.opsForZSet().reverseRange("rotation_list", 0, -1);
            logger.info("从redis获取轮播图:"+rotation_list1);
        }
        return new BaseResp(0,"查询成功",null,rotation_list1);
    }
}
